/**
 * All rights Reserved, Designed By 信鸥科技
 * project : committee
 * Created by youquer on 17/10/25.
 * 注意：本内容仅限于信鸥科技有限公司内部传阅，禁止外泄以及用于其他的商业目的
 * Description:
 *
 */

import { postList, postInfo, postUpdate, postAdd, postDelete, postAllAppList, postAppPermission } from '@/services/powers/role';
import { message } from 'antd';
import queryString from 'query-string';
import { conversionTitleByValue } from '@/utils/globalFun';
import { routerRedux } from 'dva/router';


export default {
  namespace: 'role',
  state: {
    type: "role",
    id: '', //id
    //分页
    page: 1, //当前页
    pageSize: 10, //每页条数
    total: 0, //总页数
    //列表页-添加页提交按钮loading
    loading: false,//添加页确定按钮loading
    dataList: [], //列表页数据数据
    isUpdate: 0, //是否是修改页: 0:添加页, 1:修改页
    isEnable: false, //是否可用

    //搜索部分
    //搜索字段
    values:"",
    advanceTails:{}, //高级搜索内容
    searchValue:"", //普通搜索内容
    selectValue:"name", //普通搜索
    isAdvance:false, //高级搜索暂开
    expand: false, //是否有高级搜索
    searchExpand: false, //是否存在搜索
    commonSelectData:[
      {
        value:"name",
        text:"名称"
      },
    ], //普通搜索内容,

    //树
    permissionIdsTree:[],
    permissionIds: [],
    appTree: [],
    appId: '',
    name: '',
    description: '',
    appName: '',

    //tabs标签
    key: '1', //1: 可用:标签一, 2:不可用:标签二

  },

  reducers: {

    /**
     * 赋值数据
     * */
    setState(state, action){
      return {...state, ...action.payload};
    },

    //分页act
    changePage(state, action){
      return {...state, page: action.page, pageSize: action.pageSize}
    },

    /**
     * 列表页接口-列表页函数
     * */
    //搜索
    searchData(state,action){
      if (action.key != undefined){
        state.advanceTails[action.key] = action.value;
      }

      if (action.selectValue != undefined){
        state.selectValue = action.selectValue;
      }

      //当点击搜索的时候调起接口
      if (action.searchValue != undefined){
        state.searchValue = action.searchValue;
      }
      return{...state,expand:action.expand};
    },

    //搜索重置
    advanceReset(state,action){
      return {...state,...action.payload,loading: false}
    },

    /**
     * 添加-修改页函数
     * */
    //添加成功
    addSuccess(state, action){
      return {...state,...action.payload, loading: false};
    },

    //选择姓名回调
    clickNameSuccess(state, action){
      return{...state, ...action.payload};
    },

    //添加页获取数据
    changeState(state, action){
      state[action.key] = action.value;
      return {...state, state};
    },

    //提交按钮
    submit(state,action){
      return {...state,loading:action.loading}
    },
    //提交成功
    querySuccess(state, action){

      return {...state,...action.payload, loading: false};
    },
    clearData(state){
      return {...state,
        isMenu: false,
        name: '',
        parentId: '',
        url:'',
        isEnable:'',
        sort: '',
        permissionIdsTree:[],
        permissionIds: [],
        appTree: [],
        appId: '',
        description: '',
        appName: '',
      };
    }
  },

  subscriptions: {
    //路由启动时,调用  也就是初始化页面
    setup({ dispatch, history }) {
      history.listen(location => {
        if (location.pathname === '/permissions/roleAdd'){ //跳到
          //清空数据
          dispatch({
            type: 'clearData',
          });
          dispatch({
            type: 'toAdd',
          });
          dispatch({
            type: 'setState',
            payload: {isUpdate:0}
          })
        } else if (location.pathname === '/permissions/roleEdit'){ //跳到修改页
          var search = queryString.parse(location.search);
          //清空数据
          dispatch({
            type: 'clearData',
          });
          dispatch({
            type: 'toAdd',
            payload: {id: search.id}
          });
          dispatch({
            type: 'setState',
            payload: {isUpdate: 1, id: search.id}
          })
        }  else if (location.pathname === '/permissions/role'){ //列表页
          //调用列表页方法
          dispatch({
            type: 'clearData',
          });
          dispatch({
            type: 'toAdd',
          });
          dispatch({
            type: 'dateList',
          });
        }
      });
    }
  },

  effects:{
    //列表页,分页,搜索页
    *dateList({payload}, { call, put ,select}) {
      var dates = yield select(state => state.role);
      //var params = dates.advanceTails;
      var params = {};
      params["pageSize"] = dates.pageSize;
      params["selectValue"] = dates.selectValue;
      params["searchValue"] = dates.searchValue;
      if (payload){
        params["page"] = payload;
      } else {
        params["page"] = dates.page;
      }
      const data = yield call(postList, params);
      if (data) {
        // 但是现在 我只能获取到, 纯粹的 rest 返回结果 是个数组. 我尝试在 request 类中重新封装数据, 各种尝试都失败了. 各种搜  可能是关键词不对  也没有找到解决办法.
        if (data.body && data.recode == 200){
          yield put({
            type: 'setState',
            payload: {
              dataList: data.body.dataList,
              total: data.body.total,
            }
          });
        } else if (data.recode == 9000){
          message.error("您的权限不足");
        } else if (data.recode == 1001){
          yield put(routerRedux.push("/user/login"));
        } else {
          message.error('网络请求失败!');
        }
      } else {
        message.error("网络请求失败");
      }
    },
    //获取详情信息
    *getInfo({payload}, { call, put ,select}){
      var dates = yield select(state => state.role);
      const data = yield call(postInfo, payload);
      if (data){
        if (data.recode == 200){
          if (data.body){
            data.body.role["appName"] = conversionTitleByValue(data.body.role.appId, dates.appTree);
            var permissionIds = [];
            for (var i = 0; i < data.body.role.permissions.length; i++){
              var item = data.body.role.permissions[i];
              permissionIds.push(item.id + "");
            }
            yield put({
              type: 'setState',
              payload: {permissionIds: permissionIds},
            });
            yield put({
              type: 'setState',
              payload: data.body.role,
            });
            yield put({
              type: "singleTreeCallBack",
              payload: data.body.role.appId,
              key: "appId",
              noBack: 1,
            })
          }
        } else if (data.recode == 9000){
          message.error("您的权限不足");
        } else if (data.recode == 1001){
          yield put(routerRedux.push("/user/login"));
        } else {
          message.error('网络请求失败!');
        }
      } else {
        message.error("网络请求失败");
      }
    },
    //删除
    *delete({payload}, {call, put}){
      const dic = {id: payload};
      const data = yield call(postDelete,dic);
      if (data){
        if (data.recode == 200){
          message.success("删除该条信息成功");
          yield put({
            type: 'dateList',
          });
        } else if (data.recode == 9000){
          message.error("您的权限不足");
        } else if (data.recode == 1001){
          yield put(routerRedux.push("/user/login"));
        } else {
          message.error('网络请求失败!');
        }
      } else {
        message.error("网络请求失败!");
      }
    },
    //添加修改网络请求
    *update({payload}, {call, put, select}) {
      if (payload.appId && payload.name && payload.description && payload.permissionIds.length){
        payload.id = yield select(state => state.role.id);
        const data = yield call(postUpdate,{...payload});
        if (data) {
          if (data.recode == 200){
            message.success('提交成功');
            yield put({
              type:'addSuccess',
              payload:{
                loading: false,
              }
            });
            yield put(routerRedux.push("/permissions/role"));
          } else if (data.recode == 9000){
            message.error("您的权限不足");
          } else if (data.recode == 1001){
            yield put(routerRedux.push("/user/login"));
          } else {
            message.error('网络请求失败,请重新提交');
            yield put({
              type:'submit',
              loading: false
            })
          }
        } else {
          message.error("网络请求失败");
          yield put({
            type:'submit',
            loading: false
          })
        }
      }else {
        message.warn('所有信息均为必填信息');
        yield put({
          type:'submit',
          loading: false
        })
      }
    },
    //添加接口
    *add({payload}, {call, put, select}) {
      payload["is_grade"] = 0;
      payload["grade_type"] = 0;
      payload["grade_id"] = 0;
      if (payload.appId && payload.name && payload.description && payload.permissionIds.length > 0){
        const data = yield call(postAdd, payload);
        if (data) {
          if (data.recode == 200){
            message.success('提交成功');
            yield put({
              type:'addSuccess',
              payload:{
                loading: false,
              }
            });
            yield put(routerRedux.push("/permissions/role"));
          } else if (data.recode == 9000){
            message.error("您的权限不足");
          } else if (data.recode == 1001){
            yield put(routerRedux.push("/user/login"));
          } else {
            message.error('网络请求失败,请重新提交');
            yield put({
              type:'submit',
              loading: false
            })
          }
        } else {
          message.error("网络请求失败");
          yield put({
            type:'submit',
            loading: false
          })
        }
      }else {
        message.warn('所有信息均为必填信息');
        yield put({
          type:'submit',
          loading: false
        })
      }
    },
    //获取应用数
    *toAdd({payload}, { call, put ,select}){
      var params = {
        page: 1,
        pageSize: 1000,
      };
      const data = yield call(postAllAppList, params);
      if (data){
        if (data.recode == 200){
          if (data.body.dataList){
            var appTree = [];
            for (var i = 0; i < data.body.dataList.length; i++){
              var item = data.body.dataList[i];
              var param = {
                title: item.name,
                value: item.id + "",
              };
              appTree.push(
                param
              )
            }
            yield put({
              type: 'setState',
              payload: {appTree: appTree},
            });
            if (payload){
              //获取详情
              yield put({
                type: 'getInfo',
                payload: {id: payload.id},
              });
            }
          }
        } else if (data.recode == 9000){
          message.error("您的权限不足");
        } else if (data.recode == 1001){
          yield put(routerRedux.push("/user/login"));
        } else {
          message.error('网络请求失败!');
        }
      } else {
        message.error("网络请求失败");
      }
    },
    //根据应用名获取所有权限
    *singleTreeCallBack({payload, key, noBack}, { call, put ,select}){
      if (payload){
        if (key == "appId"){
          var params = {
            isMenu: 2,
            id: payload
          };
          const data = yield call(postAppPermission, params);
          if (data){
            if (data.recode == 200){
              if (!noBack){
                yield put({
                  type: "setState",
                  payload: {permissionIds: [], permissionIdsTree: []}
                });
              }
              if (data.body.dataList){
                var appTree = [];
                for (var i = 0; i < data.body.dataList.length; i++){
                  var item = data.body.dataList[i];
                  var param = {
                    title: item.name,
                    value: item.id + "",
                  };
                  appTree.push(
                    param
                  )
                }
                yield put({
                  type: 'setState',
                  payload: {permissionIdsTree: appTree},
                })
              }
            } else if (data.recode == 9000){
              message.error("您的权限不足");
            } else if (data.recode == 1001){
              yield put(routerRedux.push("/user/login"));
            } else {
              message.error('网络请求失败!');
            }
          } else {
            message.error("网络请求失败");
          }
          //postAppPermission
        }
      } else {
        yield put({
          type: "setState",
          payload: {permissionIds: [], permissionIdsTree: []}
        })
      }

    }
  },
}
